﻿using System;
using System.Diagnostics;
using System.Windows;
using Coding4Fun.BoxingBots.Common;
using Coding4Fun.BoxingBots.Communication;

namespace Coding4Fun.BoxingBots.Scoreboard
{
	public class Robot : IDisposable
	{
		public event EventHandler<MovementOverrideChangedEventArgs> MovementOverrideChanged;

		public bool IsConnected { get { return _dataClient != null && _dataClient.IsConnected; } }
		public int Health { get; set; }
		public bool MovementOverride { get; set; }
		public bool LockSkeleton { get; set; }

		public CalculatedSensorData SensorData { get; set; }

		private SocketClient<MovementDescriptorPacket, RobotStatePacket> _dataClient;
		private bool _lastPunch;
		private bool _lastLock;

		public void Connect(string address, int port)
		{
			_dataClient = new SocketClient<MovementDescriptorPacket, RobotStatePacket>();
			_dataClient.ConnectionCompleted += DataClientConnectionCompleted;
			_dataClient.PacketReceived += DataClientPacketReceived;
			_dataClient.Connect(address, port);
		}

		public void Reset()
		{
			this.Health = Settings.MaxRobotHealth;
		}

		void DataClientConnectionCompleted(object sender, ConnectionEventArgs e)
		{
			Debug.WriteLine("Connection from ScoreBoard to BoxingBot: " + e.Connected);
			if(!e.Connected)
				MessageBox.Show("Connection from ScoreBoard to BoxingBot failed");
		}

		void DataClientPacketReceived(object sender, PacketReceivedEventArgs<RobotStatePacket> e)
		{
			Debug.WriteLine("Scoreboard RobotStatePacket: " + e.Packet);

			SensorData = e.Packet.SensorData;
			LockSkeleton = e.Packet.LockSkeleton;

			if(e.Packet.PunchDetected && !_lastPunch)
			{
				Health -= 1;
				AudioPlayer.PlayCue(SoundCue.Hit);
			}

			if(MovementOverride != e.Packet.MovementOverride)
			{
				MovementOverride = e.Packet.MovementOverride;

				if(MovementOverrideChanged != null)
					MovementOverrideChanged(this, new MovementOverrideChangedEventArgs { MovementOverride = MovementOverride });
			}

			_lastPunch = e.Packet.PunchDetected;
		}

		public void Send(MovementDescriptorPacket mdp)
		{
			if(_dataClient != null)
				_dataClient.Send(mdp);
		}

		public void Dispose()
		{
			if (_dataClient != null)
				_dataClient.Disconnect();
		}
	}
}
